package com.tiktok.controller;

import com.tiktok.dto.Result;
import com.tiktok.entity.User;
import com.tiktok.service.UserService;
import com.tiktok.utils.UserContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户头像管理控制器
 */
@RestController
@RequestMapping("/user/avatar")
@RequiredArgsConstructor
@Slf4j
public class UserAvatarController {

    private final UserService userService;
    private final FileUploadController fileUploadController;

    /**
     * 上传并更新用户头像
     */
    @PostMapping("/upload")
    public Result<Map<String, Object>> uploadAndUpdateAvatar(@RequestParam("file") MultipartFile file) {
        
        Long userId = UserContext.getUserId();
        if (userId == null) {
            return Result.unauthorized();
        }

        try {
            // 上传头像文件
            Result<Map<String, Object>> uploadResult = fileUploadController.uploadAvatar(file);
            if (uploadResult.getCode() != 200) {
                return uploadResult;
            }

            // 获取上传后的头像URL
            String avatarUrl = (String) uploadResult.getData().get("avatarUrl");
            
            // 更新用户头像
            User currentUser = userService.getById(userId);
            if (currentUser == null) {
                return Result.error("用户不存在");
            }

            // 保存旧头像URL用于返回
            String oldAvatarUrl = currentUser.getAvatar();
            
            // 更新头像
            currentUser.setAvatar(avatarUrl);
            boolean updateSuccess = userService.updateById(currentUser);
            
            if (!updateSuccess) {
                return Result.error("更新用户头像失败");
            }

            // 构造返回数据
            Map<String, Object> result = new HashMap<>();
            result.put("avatarUrl", avatarUrl);
            result.put("oldAvatarUrl", oldAvatarUrl);
            result.put("originalName", uploadResult.getData().get("originalName"));
            result.put("fileName", uploadResult.getData().get("fileName"));
            result.put("fileSize", uploadResult.getData().get("fileSize"));
            result.put("userId", userId);

            return Result.success("头像更新成功", result);

        } catch (Exception e) {
            log.error("上传头像失败", e);
            return Result.error("上传头像失败：" + e.getMessage());
        }
    }

    /**
     * 获取当前用户头像信息
     */
    @GetMapping("/current")
    public Result<Map<String, Object>> getCurrentUserAvatar() {
        
        Long userId = UserContext.getUserId();
        if (userId == null) {
            return Result.unauthorized();
        }

        try {
            User currentUser = userService.getById(userId);
            if (currentUser == null) {
                return Result.error("用户不存在");
            }

            Map<String, Object> result = new HashMap<>();
            result.put("userId", userId);
            result.put("avatarUrl", currentUser.getAvatar());
            result.put("nickname", currentUser.getNickname());
            result.put("username", currentUser.getUsername());

            return Result.success(result);

        } catch (Exception e) {
            log.error("获取用户头像失败", e);
            return Result.error("获取用户头像失败：" + e.getMessage());
        }
    }

    /**
     * 获取指定用户头像信息
     */
    @GetMapping("/user/{userId}")
    public Result<Map<String, Object>> getUserAvatar(@PathVariable Long userId) {
        
        if (userId == null || userId <= 0) {
            return Result.badRequest("用户ID无效");
        }

        try {
            User user = userService.getById(userId);
            if (user == null) {
                return Result.notFound();
            }

            Map<String, Object> result = new HashMap<>();
            result.put("userId", userId);
            result.put("avatarUrl", user.getAvatar());
            result.put("nickname", user.getNickname());
            result.put("username", user.getUsername());

            return Result.success(result);

        } catch (Exception e) {
            log.error("获取用户头像失败: userId={}", userId, e);
            return Result.error("获取用户头像失败：" + e.getMessage());
        }
    }

    /**
     * 重置用户头像为默认头像
     */
    @PostMapping("/reset")
    public Result<Map<String, Object>> resetAvatar() {
        
        Long userId = UserContext.getUserId();
        if (userId == null) {
            return Result.unauthorized();
        }

        try {
            User currentUser = userService.getById(userId);
            if (currentUser == null) {
                return Result.error("用户不存在");
            }

            // 保存旧头像URL
            String oldAvatarUrl = currentUser.getAvatar();
            
            // 设置默认头像
            String defaultAvatarUrl = "/api/files/avatar/default/avatar.jpg";
            currentUser.setAvatar(defaultAvatarUrl);
            
            boolean updateSuccess = userService.updateById(currentUser);
            if (!updateSuccess) {
                return Result.error("重置头像失败");
            }

            Map<String, Object> result = new HashMap<>();
            result.put("avatarUrl", defaultAvatarUrl);
            result.put("oldAvatarUrl", oldAvatarUrl);
            result.put("userId", userId);

            return Result.success("头像已重置为默认头像", result);

        } catch (Exception e) {
            log.error("重置头像失败", e);
            return Result.error("重置头像失败：" + e.getMessage());
        }
    }
} 